package handler

import (
	"context"
	"dh.com/store/srv/goods/proto/goods"
	"github.com/google/uuid"
	"github.com/micro/go-micro/client"
	"github.com/micro/go-micro/errors"
)

//Goods
type Goods struct {
	Client client.Client
}

var _goods []*goods.GoodsDTO

//NewGoods
func NewGoods(client client.Client) *Goods {
	return &Goods{Client: client}
}

func (g *Goods) Add(_ context.Context, req *goods.GoodsDTO, _ *goods.NullResponse) error {
	req.Id = uuid.New().String()
	_goods = append(_goods, req)
	return nil
}

func (g *Goods) Update(_ context.Context, req *goods.GoodsDTO, _ *goods.NullResponse) error {
	var flg = false
	for i, v := range _goods {
		if v.Id == req.Id {
			flg = true
			_goods[i] = req
			return nil
		}
	}
	if flg {
		return errors.InternalServerError("com.dh.store.srv.goods", "商品[ID:%s]不存在！", req.Id)
	}
	return nil
}

func (g *Goods) Delete(_ context.Context, req *goods.KeyRequest, _ *goods.NullResponse) error {
	for i, v := range _goods {
		if req.Id == v.Id {
			_goods = append(_goods[:i], _goods[i+1:]...)
			return nil
		}
	}
	return nil
}

func (g *Goods) FindOne(_ context.Context, req *goods.KeyRequest, rsp *goods.FindOneResponse) error {
	for _, v := range _goods {
		if req.Id == v.Id {
			rsp.Goods = v
			return nil
		}
	}
	return nil
}

func (g *Goods) FindAll(ctx context.Context, _ *goods.NullRequest, rsp *goods.FindAllResponse) error {
	rsp.Goods = _goods

	//p := micro.NewPublisher("com.dh.store.srv.log", g.Client)
	//err := p.Publish(context.Background(), &log1.Message{Say: "123"})
	//if err != nil {
	//	log.Fatal(err)
	//}
	//log.Info("OOOOOOOO=====")

	return nil
}
